package cn.cvs.servlet;

import cn.cvs.dao.PowerBatteryMapper;
import cn.cvs.pojo.PowerBattery;
import cn.cvs.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet (urlPatterns = "/UpdateServlet")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();

        SqlSession sqlSession = MyBatisUtil.createSqlSession();
        PowerBatteryMapper powerBatteryMapper = sqlSession.getMapper(PowerBatteryMapper.class);
        PowerBattery powerBattery = new PowerBattery();
        powerBattery.setCarName(req.getParameter("carName"));
        powerBattery.setCityName(req.getParameter("cityName"));
        powerBattery.setUserName(req.getParameter("userName"));
        powerBattery.setPressureValue(Integer.parseInt(req.getParameter("pressureValue")));
        powerBattery.setTime(req.getParameter("time"));
        powerBattery.setId(Integer.parseInt(req.getParameter("id")));
        int num = 0;
        try {
            num = powerBatteryMapper.update(powerBattery);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        if (num>0){
            out.print("<script>\n" +
                    "    location.href='PowerList';\n" +
                    "    alert('修改成功!')\n" +
                    "  </script>");
        }else {
            out.print("<script>\n" +
                    "    location.href='PowerList';\n" +
                    "    alert('修改失败!')\n" +
                    "  </script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
